package be.scond.cartpool;

import java.io.IOException;
import java.math.BigDecimal;

import javax.servlet.http.*;
import be.scond.cartpool.API.ShoppingListApi;
import be.scond.cartpool.exceptions.OrderDoesNotExistException;
import be.scond.cartpool.model.Order;

public class UpdateOrderServlet extends HttpServlet {
	
	static final long serialVersionUID = 1;
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/xml");		
		
		String respons = "<data>";	

		Order order = null;
		String errorResp = "";
		String noticeResp = "";
		String keyString = req.getParameter("key");
		String product = req.getParameter("product");
		String description = req.getParameter("description");
		
		int quantity;
		BigDecimal price;
		try {
			price = BigDecimal.valueOf(Double.parseDouble(req.getParameter("price")));
		} catch (NumberFormatException e) {
			price = null;
		}catch (NullPointerException e) {
			price = null;
		}
		
		try {
			quantity = Integer.parseInt(req.getParameter("quantity"));
		} catch (NumberFormatException e) {
			quantity = -1;
		} 
		
		if(product != null){
			try {
				order = ShoppingListApi.updateOrder(keyString, product);
				noticeResp = "product was updated";
			} catch (OrderDoesNotExistException e) {
				errorResp = "tried updating product.";
			}
		}
		
		if(description != null){
			try {
				order = ShoppingListApi.updateOrderDescription(keyString, description);
				noticeResp = "description was updated";
			} catch (OrderDoesNotExistException e) {
				errorResp = "tried updating description.";
			}
		}
		
		if(price != null){
			try {
				order = ShoppingListApi.updateOrder(keyString, price);
				noticeResp = "price was updated";
			} catch (OrderDoesNotExistException e) {
				errorResp = "tried updating price.";
			}
		}
		
		if(quantity != -1){
			try {
				order = ShoppingListApi.updateOrder(keyString, quantity);	
				noticeResp = "quantity was updated";
			} catch (OrderDoesNotExistException e) {
				errorResp = "tried updating quantity.";
			}
		}			
		if(order == null){
			respons += "<error>"+errorResp+" Order to update was not found</error>";
		}else{
			respons += "<succes>"+noticeResp+"</succes>";
			respons += order.toXmlString();							
		}
			
		respons += "</data>";

		resp.getWriter().print(respons);
	}
}